const request = require('request')
const crypto = require('crypto')
const config = require('../../config')

module.exports = {
    request,
    setMd5(value) {
        return crypto.createHash('md5').update(value).digest('hex')
    },
    /**
     * 封装request请求
     */
    requestAsync(options) {
        return new Promise((reslove, reject) => {
            request(options, (err, res, body) => {
                if (err) return reject(err)
                return reslove(body)
            })
        })
    },

    access(path,method,options) {
        let appid = config.platform.appid;
        let secret = config.platform.secret; //TODO：密钥+时间戳+参数  MD5加密
        let baseURL = config.openapi.baseURL;
        let timestamp = Date.now();
        let url = `${baseURL}${path}?appid=${appid}&secret=${secret}&timestamp=${timestamp}`
        let _options = {
            url: url,
            method: method,
            json:true
        };
        if(options){
            _options = Object.assign(_options,options);
        }
        return this.requestAsync(_options);
    },

    post(url,body) {
        return this.access(url,'post',{form:body});
    },

    get(url,params) {
        return this.access(url,'get',{qs:params});
    },

    put(url,body) {
        return this.access(url,'put',{form:body});
    },

    delete(url,body) {
        return this.access(url,'delete',{form:body});
    }
}